package com.hznu.googleAuthenticatorDemo.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hznu.googleAuthenticatorDemo.common.cryptolib.CryptoApp;
import com.hznu.googleAuthenticatorDemo.common.utils.PublicUtils;
import com.hznu.googleAuthenticatorDemo.entity.User;
import com.hznu.googleAuthenticatorDemo.mybeans.LoginInfo;
import com.hznu.googleAuthenticatorDemo.mybeans.R;
import com.hznu.googleAuthenticatorDemo.service.UserService;
import com.hznu.googleAuthenticatorDemo.service.base.AuthVerify;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  登录控制器
 * </p>
 *
 * @author DragonDoor
 * @since 2018-11-26
 */
@Controller
@RequestMapping("/login")
@Api(description = "登录管理接口",value = "login")
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    AuthVerify authVerify;

    @ApiOperation("用户登录")
    @RequestMapping(value = "/toLogin", method = RequestMethod.POST)
    @ResponseBody
    public R loginForm(@RequestBody LoginInfo loginInfo)
    {
        try
        {
            User user = userService.selectOne(new EntityWrapper<User>().eq("username",loginInfo.getUsername()));
            if(authVerify.passwordVerify(loginInfo.getPassword(),user))
            {
                return R.ok().put("data",user);
            }
            return R.error();
        }catch (Exception e)
        {
            e.printStackTrace();
            return R.error();
        }
    }

    @ApiOperation("谷歌身份验证")
    @GetMapping("/googleVerify/{id}/{code}")
    @ResponseBody
    public R googleVerify(@PathVariable Integer id,@PathVariable long code)
    {
        try
        {
            if(authVerify.googleAuthVerify(id,code))
            {
                return R.ok();
            }

            return R.error();
        }catch (Exception e)
        {
            return R.error();
        }
    }


}
